﻿using Azrng.Swashbuckle;
using Common.Core;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.OpenApi.Models;
using NetByDocker.Store.InMemory;
using NetByDocker.Domain.Npgsql;
using System.Reflection;
using NetByDocker.Filters;
using NetByDocker.Store.Npgsql;
using StackExchange.Profiling.Storage;

namespace NetByDocker;

public class Startup
{
    public Startup(IConfiguration configuration, IWebHostEnvironment environment)
    {
        Configuration = configuration;
        Environment = environment;
    }

    private IConfiguration Configuration { get; }

    private IWebHostEnvironment Environment { get; }

    public void RegisterServices(IServiceCollection services)
    {
        Console.WriteLine("RegisterServices start");

        // Add Service
        services.AddControllers(options =>
                {
                    // 自定义框架绑定器
                    //options.ModelBinderProviders.Insert(0, new TokenModelBinderProvider());
                    //options.Filters.Add<ModelVerifyFilter>(); //  services.AddMvcModelVerifyFilter() 已经添加
                })
                .AddNewtonsoftJson(options =>
                {
                    //时间格式化
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";

                    // 设置自定义序列化
                    //options.SerializerSettings.ContractResolver = new CustomContractResolver();
                });

        services.AddMvcModelVerifyFilter()
                .AddEndpointsApiExplorer()
                .AddMvcResultPackFilterFilter();

        services.AddDefaultSwaggerGen()
                .AddAnyCors()
                .ConfigureDefaultJson(option => { });

        //完整访问地址：http://localhost:5000/profiler/results-index
        services.AddMiniProfiler(options =>
        {
            options.PopupShowTimeWithChildren = true; // 控制是否在MiniProfiler的弹出窗口中显示“Time With Children”(包括其所有子操作的总耗时)这一列
            options.PopupShowTrivial = true; // 是否显示那些执行时间非常短的操作
            options.RouteBasePath = "/profiler"; // 配置路由基础路径，默认地址是/mini-profiler-resources

            //数据缓存时间
            ((options.Storage as MemoryCacheStorage)!).CacheDuration = TimeSpan.FromMinutes(60);

            //sql格式化设置
            options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter();

            //跟踪连接打开关闭
            options.TrackConnectionOpenClose = true;

            //界面主题颜色方案;默认浅色
            options.ColorScheme = StackExchange.Profiling.ColorScheme.Dark;

            //.net core 3.0以上：对MVC过滤器进行分析
            options.EnableMvcFilterProfiling = true;

            //对视图进行分析
            options.EnableMvcViewProfiling = true;

            //控制访问页面授权，默认所有人都能访问
            //options.ResultsAuthorize;
            //要控制分析哪些请求，默认说有请求都分析
            //options.ShouldProfile;

            //内部异常处理
            //options.OnInternalError = e => MyExceptionLogger(e);
        });

        var connType = Configuration["DbConfig:EnabledDb"];
        switch (connType)
        {
            case "Postgresql":
                services.AddPgSqlDbContextService(Configuration);
                break;

            default:
                services.AddInMemoryDbContextService(Configuration);
                break;
        }

        //注入AutoMapper
        services.AddAutoMapper(Assembly.GetExecutingAssembly()
                                       .DefinedTypes.Where(t => typeof(Profile).GetTypeInfo()
                                                                               .IsAssignableFrom(t.AsType()))
                                       .Select(t => t.AsType())
                                       .ToArray());

        //IOC
        services.RegisterBusinessServices("NetByDocker.dll");
        services.AddTransient<IStartupFilter, CustomerStartupFilter>();

        services.AddHealthChecks();

        Console.WriteLine("RegisterServices end");
    }

    public void SetupMiddlewares(WebApplication app, IWebHostEnvironment env)
    {
        Console.WriteLine("SetupMiddlewares start");
        app.UseMiniProfiler();

        app.UseDefaultSwagger();

        app.UseCustomExceptionMiddleware();
        app.UseAnyCors();
        app.UseAuthorization();

        app.MapControllers();

        Console.WriteLine("SetupMiddlewares end");
    }
}